<template>
  <!-- 分配用户数据权限对话框 -->
  <el-dialog
    v-model="openDataScope"
    title="数据权限"
    width="500px"
    append-to-body
  >
    <el-form ref="dataAccessRef" :model="dataAccessForm" label-width="80px">
      <el-form-item label="用户名称">
        <el-input v-model="dataAccessForm.userName" :disabled="true" />
      </el-form-item>
      <el-form-item label="权限字符">
        <el-input v-model="dataAccessForm.permissionKey" :disabled="true" />
      </el-form-item>
      <el-form-item label="权限范围">
        <el-select v-model="dataAccessForm.dataScope" placeholder="请选择权限范围">
          <el-option
            v-for="item in dataScopeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item v-show="dataAccessForm.dataScope == 2" label="数据权限">
        <el-col><el-checkbox v-model="dataAccessForm.deptCheckStrictly">父子联动</el-checkbox></el-col>
        <el-button @click="handleTest">测试</el-button>
        <el-tree
          ref="deptRef"
          :data="deptOptions"
          show-checkbox
          class="tree_border"
          node-key="id"
          empty-text="加载中，请稍后"
          :props="{ label: 'label', children: 'children' }"
        ></el-tree>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitDataScope">确 定</el-button>
        <el-button @click="cancelDataScope">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, getCurrentInstance, watch, defineExpose, computed, toRefs } from 'vue'
import { ElMessage } from 'element-plus'
import type { ElTree } from 'element-plus'
import { getUser, updateDataScope, userDeptTreeselect, treeselect } from '@/api/system/user'

const props = defineProps<{
  initDeptOptions;
}>()
// 分配权限
const openDataScope = ref(false)
// 获取部门权限
const { initDeptOptions: deptOptions } = toRefs(props)
const deptRef = ref<InstanceType<typeof ElTree>>()
// 用户数据权限
const dataAccessForm = ref({
    userId: undefined,
    userName: undefined,
    permissionKey: undefined,
    dataScope: undefined,
    deptCheckStrictly: true,
    deptIds: [],
  }),
  dataAccessRef = ref(null),
  {
    proxy,
  }:{
    proxy:any
  } = getCurrentInstance()

// 分配部门权限
const getUserDeptTreeselect = (id) => userDeptTreeselect(id).then(res => {
  deptOptions.value = res.data.dept
  return res
})
// 重置数据权限表单
const resetDataScope = () => {
  if (deptRef.value != null) {
    deptRef.value.setCheckedKeys([])
  }
  dataAccessForm.value = {
    userId: undefined,
    userName: undefined,
    permissionKey: undefined,
    dataScope: undefined,
    deptCheckStrictly: true,
    deptIds: [],
  }
  proxy.$resetForm(dataAccessRef.value)
}
const getList = (id) => {
  getUser(id).then((res) => {
    dataAccessForm.value = res.data.data
  })
}
/** 数据范围选项 */
const dataScopeOptions = ref([
  { value: 1, label: '全部数据权限' },
  { value: 2, label: '自定数据权限' },
  { value: 3, label: '本部门数据权限' },
  { value: 4, label: '本部门及以下数据权限' },
  { value: 5, label: '仅本人数据权限' },
])
const emit = defineEmits(['changeList'])
const handleTest = () => {
  const res = deptRef.value.setCheckedKeys([100, 313, 310])
  console.log(res, 'ok')
}
/** 所有部门节点数据 */
function getDeptAllCheckedKeys() {
  //	若节点可被选择（即 show-checkbox 为 true），则返回目前半选中的节点的 key 所组成的数组
  const checkedKeys = deptRef.value.getHalfCheckedKeys()
  //  若节点可被选择（即 show-checkbox 为 true），则返回目前被选中的节点的 key 所组成的数组
  const halfCheckedKeys = deptRef.value.getCheckedKeys()
  checkedKeys.unshift(...halfCheckedKeys)
  return checkedKeys 
}
/** 提交按钮（数据权限） */
function submitDataScope() {
  if (dataAccessForm.value.userId != undefined) { 
    dataAccessForm.value.deptIds = getDeptAllCheckedKeys()
    updateDataScope(dataAccessForm.value).then(res => {
      if (res.code == 200) {
        ElMessage.success('修改成功')
        openDataScope.value = false
        emit('changeList')
      } else {
        ElMessage.error(res.msg)
      }
    })
  }
}
/** 取消按钮（数据权限） */
function cancelDataScope() {
  openDataScope.value = false
  resetDataScope()
}
defineExpose({
  getList,
  openDataScope,
  getUserDeptTreeselect,
  dataAccessForm,
  deptRef,
})
</script>
<style scoped lang="less">
.tree_border {
  border: 0 solid #ccc;
  border-radius: 5px;
}
</style>
